<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌" prop="carId">
        <el-input v-model="queryParams.carId" placeholder="请输入车牌" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车型类型" prop="carType">
        <el-select filterable v-model="queryParams.carType" placeholder="请选择车型类型" clearable>
          <el-option v-for="dict in dict.type.car_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车辆状态" prop="carState">
        <el-select v-model="queryParams.carState" placeholder="请选择车辆状态" clearable>
              <el-option v-for="option in carState" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
      </el-form-item>

      <el-form-item label="驾驶员" prop="driverUuid">
        <el-select filterable v-model="queryParams.driverUuid" placeholder="请选择驾驶员" clearable>
          <el-option v-for="driver in drivers" :key="driver.driverUuid" :label="driver.driverName"
            :value="driver.driverUuid" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['car:car:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['car:car:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆uuid编号" align="center" prop="carUuid" />
      <el-table-column label="车牌" align="center" prop="carId" />
      <el-table-column label="车辆类型" align="center" prop="carTypeDesc" />
      <el-table-column label="驾驶员姓名" align="center" prop="driverName" />
      <el-table-column label="行驶证号码" align="center" prop="carRegNumber" />
      <el-table-column label="实载重量(T)" align="center" prop="carLoadCapacity" />
      <el-table-column label="实载体积(方)" align="center" prop="carLoadVolume" />
      <el-table-column label="gps设备id" align="center" prop="gpsId" />
       <el-table-column label="车辆状态" align="center" prop="carState">
        <template slot-scope="scope">
          <span :class="scope.row.carState === '1' ? 'paid' : 'not-paid'">{{ scope.row.carState ===
            "1" ? '启用' : '暂停' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updatedBy" />
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['car:car:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['car:car:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改;对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="驾驶员" prop="driverUuid">
          <el-select filterable v-model="form.driverUuid" placeholder="请选择驾驶员" clearable>
            <el-option v-for="driver in drivers" :key="driver.driverUuid" :label="driver.driverName"
              :value="driver.driverUuid" />
          </el-select>
        </el-form-item>
        <el-form-item label="行驶证号码" prop="carRegNumber">
          <el-input v-model="form.carRegNumber" placeholder="请输入行驶证号码" />
        </el-form-item>
        <el-form-item label="车牌" prop="carId">
          <el-input v-model="form.carId" placeholder="请输入车牌" />
        </el-form-item>
        <el-form-item label="车型类型" prop="carType">
          <el-select v-model="form.carType" placeholder="请选择车型类型" clearable>
            <el-option v-for="dict in dict.type.car_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实载重量(T)" prop="carLoadCapacity">
          <el-input v-model="form.carLoadCapacity" placeholder="请输入实载重量(T)" />
        </el-form-item>
        <el-form-item label="实载体积(方)" prop="carLoadVolume">
          <el-input v-model="form.carLoadVolume" placeholder="请输入实载体积(方)" />
        </el-form-item>
        <el-form-item label="gps设备id" prop="gpsId">
          <el-input v-model="form.gpsId" placeholder="请输入gps设备id" />
        </el-form-item>
        <el-form-item label="车辆状态" prop="carState">
        <el-select v-model="form.carState" placeholder="请选择车辆状态" clearable>
              <el-option v-for="option in carState" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
      </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCar, getCar, delCar, addCar, updateCar ,isLicensePlateRegistered} from "@/api/carManager/car";
import { selectAllDriverlist } from "@/api/fincal/driver";
export default {
  name: "Car",
  dicts: ['car_type'],
  data() {
    return {
      carState: [
        { value: "1", label: '启用' },
        { value: "0", label: '暂停' }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ;表格数据
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用于保存驾驶员列表
      drivers: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carId: "",
        carType: "",
        carLoadCapacity: "",
        carLoadVolume: "",
        gpsId: "",
        carState: "1",
        driverUuid: "",
        carRegNumber: ""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        carId: [
          { required: true, message: "车牌号不能为空", trigger: "blur" },
          {
            async validator(rule, value, callback) {
              try {
                const response = await isLicensePlateRegistered({carId:value});  
                if (response.msg==="true") {
                  return callback(new Error('该车牌号已被录入'));
                }
                callback();  // 校验通过
              } catch (error) {
                callback(new Error('车牌号校验失败，请稍后再试'));
              }
            },
            trigger: 'blur'
          }
        ],
        driverUuid: [
          { required: true, message: "驾驶员不能为空", trigger: "blur" },
        ]
        
      }
    };
  },
  created() {
    this.getList();
    this.loadDrivers(); // 加载驾驶员数据
  },
  methods: {
    /** 查询;列表 */
    getList() {
      this.loading = true;
      listCar(this.queryParams).then(response => {
        this.carList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: "",
        carType: "",
        carLoadCapacity: "",
        carLoadVolume: "",
        gpsId: "",
        carState: "1",
        driverUuid: "",
        carRegNumber: ""
      };
      this.resetForm("form");
    },
    /** 加载驾驶员列表 */
    loadDrivers() {
      this.loading = true;
      selectAllDriverlist(this.queryParams).then(response => {
        this.drivers = response.data;
        this.loading = false;
      }).catch((error) => {
        console.error("获取驾驶员列表失败:", error);
        this.loading = false;
      });
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加;";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCar(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改;";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCar(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCar(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除;编号为"' + ids + '"的数据项？').then(function () {
        return delCar(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fincal/car/export', {
        ...this.queryParams
      }, `car_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.paid {
  color: green;
  font-weight: bold;
  /* 可选，用于突出显示 */
}

.not-paid {
  color: red;
  font-weight: bold;
  /* 可选，用于突出显示 */
}
</style>
